import axios from 'axios'
import { Message } from 'element-ui'
import {getToken} from '@/utils/helpers'
import router from '@/router'
import {BASE_SERVER_URL} from './config'
import store from '@/store'

const BASE_URL = BASE_SERVER_URL + '/api'
const http = axios.create({
  baseURL: BASE_URL,
  timeout: 15000
})

http.interceptors.request.use(config => {
  config.headers['Authorization'] = 'Bearer ' + getToken()
  return config
}, error => {
  return Promise.reject(error)
})

http.interceptors.response.use((response) => {
  // Do something with response data
  return response
}, (error) => {
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        error.message = '请求错误'
        break
      case 401:
        if (router.currentRoute.path !== '/login') {
          store.commit('SET_TOKEN', '')
          router.push('/login')
        }
        break
      case 403:
        error.message = '拒绝访问'
        break
      case 404:
        error.message = `请求地址出错: ${error.response.config.url}`
        break
      case 422:
        if (error.response.data.errors) {
          for (var key in error.response.data.errors) {
            error.message = error.response.data.errors[key][0]
            break
          }
        }
        break
      default:
    }
    let msg = error.response.data.message ? error.response.data.message : error.message
    Message({
      message: msg,
      type: 'error',
      duration: 3000
    })
  }
  return Promise.reject(error)
})
export default http
